﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

using SManaModel.dtos;
using SManaModel.entities;
using SManaModel.models;

using System;
using System.Linq.Expressions;
using SManaModel.utils;

namespace SManaApi.Services
{
    public class NotifyService : BaseService<NotifyEntity>
    {
        public NotifyService(MyDbContext dbContext) : base(dbContext)
        {
        }

        public int Add(NotifyEntity entity)
        {
            _dbContext.Notify.Add(entity);
            var num = _dbContext.SaveChanges();
            return num;
        }

        public int Delete(int id)
        {
            var entity = new NotifyEntity()
            {
                Id = id,
            };
            _dbContext.Notify.Remove(entity);
            var num = _dbContext.SaveChanges();
            return num;
        }
        
        public NotifyDto? GetNotify(Expression<Func<NotifyEntity, bool>> whereExpression)
        {
            var entities = base.GetEntity(whereExpression);
            var outEntity = entities?.Join(_dbContext.Account!, entity => entity.PublishId, entity => entity.Id, (notify, account) => new NotifyDto
            {
                id = notify.Id,
                title = notify.Title,
                content = notify.Content,
                cdate = notify.CDate,
                type = notify.PublishType,
                level = notify.PublishLevel,
                name = account.Name ?? account.UserName
            })?.FirstOrDefault();
            return outEntity;
        }
    }
}
